<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .router-link-active{
      background-color: red;
    }
  </style>
</head>
<body>
  <div id="app">
    <router-link to="/home" tag="button">首页</router-link>
    <router-link to="/news" tag="button">新闻</router-link>
    <router-link to="/about" tag="button">关于我们</router-link>
    <hr>
    <router-view></router-view>
  </div>
  <script src="./vue.js"></script>
  <script src="./vue-router.js"></script>
  <script>
    const Home = {
      template: `
        <div>
          <h1>
            首页
          </h1>
        </div>
      `
    }
    const News = {
      template: `
        <div>
          <h1>
            新闻页
          </h1>
        </div>
      `
    }
    const About = {
      template: `
        <div>
          <h1>
            关于我们
          </h1>
        </div>
      `
    }
    const Login = {
      template: `
        <div>
          <h1>
            登录页
            <button @click="doLogin">登录</button>
          </h1>
        </div>
      `,
      methods: {
        doLogin(){
          // 直接请求成功 返回token
          
          setTimeout(()=>{
            const token = 'dhwidjwd989';
            localStorage.setItem('token', token);
            this.$router.push('/home')
          },1000)
        }
      }
    }
    // 创建路由对象
    const routes = [
      {
        path: '/login',
        component: Login
      },
      {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        component: Home
      },
      {
        path: '/news',
        component: News
      },
      {
        path:'/about',
        component: About
      }
    ]
    const router = new VueRouter({
      routes
    })
    router.beforeEach((to, from, next)=>{
      // 做登录鉴权 
      /* 
      原理：
        获取登录成功 缓存的 token，判断是否有token
        有登录了
        没有 没有登录 重定向到登录页
      登录页注册 路由一定 不能判断是否登录才能访问而应该直接放行
      */
      if(to.fullPath === '/login' || to.fullPath === '/register'){
        next()
      }
      const token = localStorage.getItem('token');
      if(token){
        next();
      }else{
        // 没有登录
        next('/login')
      }
      
    })
    const vm = new Vue({
      el:'#app',
      router
    })
  </script>
</body>
</html>